﻿using LuDragon.Common.Constant;
using LuDragon.Common.Enums;
using LuDragon.Common.Utils;
using LuDragon.IService.System;
using LuDragon.Service.System;
using System;
using System.Web;
using System.Web.Mvc;

namespace LuDragon.Web.Areas.Admin.Filters
{
    public class GlobalExceptionAttribute : HandleErrorAttribute
    {
        public override void OnException(System.Web.Mvc.ExceptionContext filterContext)
        {
            IUserService userService = new UserService();
            var AdminInfo = userService.GetCurrentUser();
            if (AdminInfo == null)
            {
                filterContext.Result = new RedirectResult($"/Admin/Login/Index");
            }
            else
            {
                filterContext.Result = SendMsg(filterContext.Exception, "", filterContext);
            }
            filterContext.ExceptionHandled = true;
        }

        #region  根据是否为异步请求 返回不同的消息 +ActionResult SendMsg(string strMsg, string strBackUrl)
        /// <summary>
        ///  根据是否为异步请求 返回不同的消息
        /// </summary>
        /// <param name="strMsg"></param>
        /// <param name="strBackUrl"></param>
        /// <returns></returns>
        System.Web.Mvc.ActionResult SendMsg(Exception ex, string strBackUrl, System.Web.Mvc.ExceptionContext filterContext)
        {
            HttpException httpException = new HttpException(null, ex);
            var code = httpException.GetHttpCode();
            if (ex != null && filterContext.HttpContext.Request.IsAjaxRequest())
            {
                return new JsonResult()
                {
                    //Data = new { success = false, message = ex.Message },
                    Data = new HttpResult { Code = 500, Msg = ex.Message },
                    JsonRequestBehavior = System.Web.Mvc.JsonRequestBehavior.AllowGet
                };
            }
            else
            {
                return new RedirectResult($"/Admin/Common/Error?code={code}&msg={ex.Message.Replace("\n", "")}");
            }
        }

        #endregion


    }
}